
package cn.edu.ctbu.sbadmin.grade.api;

import cn.edu.ctbu.sbadmin.common.controller.BaseRestController;
import cn.edu.ctbu.sbadmin.common.domain.QueryPagePara;
import cn.edu.ctbu.sbadmin.common.utils.*;
import cn.edu.ctbu.sbadmin.grade.domain.TeacherDO;
import cn.edu.ctbu.sbadmin.grade.service.TeacherService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @author Fromtech
 * @email tms@fromtech.net
 * @date 2018-11-19 15:45:15
 */
@RestController
@RequestMapping("/api/grade/teacher")
@Slf4j
@Api(value = "教师管理", tags = {"教师管理"})
public class TeacherRestController extends BaseRestController {
    @Autowired
    private TeacherService teacherService;

    /**
     * 为select2准备的数据查询
     *
     * @param q
     * @return
     * @throws Exception
     */
    @RequestMapping("queryByQ")
    @RequiresPermissions("grade:teacher:list")
    public List<TeacherDO> queryByQ(@RequestParam(value = "q", defaultValue = "") String q) throws Exception {
        QueryWrapper<TeacherDO> teacherDOQueryWrapper = new QueryWrapper<TeacherDO>();
        teacherDOQueryWrapper.like("name",q);
        List<TeacherDO> teacherDOList = teacherService.list(teacherDOQueryWrapper);
        return teacherDOList;
    }

    /**
     * 根据 id取记录
     */
    @RequestMapping("/get")
    @RequiresPermissions("grade:teacher:list")
    public R get(Integer id) {
        TeacherDO config = teacherService.getById(id);

        if (config != null) {
            return R.ok("data", config);
        }
        return R.error(-1, "出错了，找不到此数据!");
    }

    /**
     * 取所有记录
     */
    @RequestMapping("/getAll")
//    @RequiresPermissions("grade:teacher:list")
    public R getAll() throws Exception {
        List<TeacherDO> teacherDOList = teacherService.getAll();
        return R.ok("data", teacherDOList);
    }

    /**
     * 根据条件分页取所有记录
     */
    @RequestMapping("/getByPage")
    @RequiresPermissions("grade:teacher:list")
    public PageUtils list(@RequestParam("where") String where,
                          @RequestParam("pageSize") Integer pageSize,
                          @RequestParam("pageIndex") Integer pageIndex,
                          @RequestParam("sort") String sort,
                          @RequestParam("direct") String direct) throws Exception {
        //首先，把where条件的参数转为QueryAndItems
        //其中,where条件需要我们自己组装.示例:
        //name=张^:like&time=2^:lg&dmtCreate=2017-01-01^^2018-01-01
        //这个表示:
        //(name like '%张%' )and ( time<2 ) and (dmtCreate between '2017-01-01' and '2018-01-01)

        QueryPagePara mQuery = QueryParaHelper.GenQuery(where, pageSize, pageIndex, sort, direct);

        IPage<TeacherDO> teacherDOList = teacherService.getByPage(mQuery);

        PageUtils pageUtils = new PageUtils(teacherDOList.getRecords(),
                teacherDOList.getTotal());

        return pageUtils;
    }


    /**
     * 保存记录
     */
    @PostMapping("/save")
    @RequiresPermissions("grade:teacher:add")
    public R save(TeacherDO teacherDO) {
        teacherDO.setPassword(MD5Utils.encrypt(teacherDO.getUsername(), teacherDO.getPassword()));   //对用户的密码在客户端进行MD5加密
        teacherDO.setGmtCreate(new Date());
        teacherDO.setIsDeleted(0);
      //teacherDO.set(getUser().getId());
        if (teacherService.save(teacherDO) ) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改记录
     */
    @RequestMapping("/update")
    @RequiresPermissions("grade:teacher:edit")
    public R update(TeacherDO teacherDO) {

        String teacherDOSno = teacherDO.getUsername();
        String password = teacherDO.getPassword();

        if (!password.isEmpty() && password != "") {
            //密碼不为空
            teacherDO.setPassword(MD5Utils.encrypt(teacherDOSno, password));   //对用户的密码在客户端进行MD5加密
        } else {
            //密碼为空
            teacherDO.setPassword(teacherService.getPassword(teacherDO.getId()));//通过id获取其密码并重设
        }
        teacherDO.setGmtModified(new Date());
        teacherService.updateById(teacherDO);
        return R.ok();
    }


    /**
     * 逻辑删除记录
     */
    @PostMapping("/remove")
    @RequiresPermissions("grade:teacher:remove")
    public R remove(Integer id) {
        if (teacherService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 逻辑删除
     */
    @PostMapping("/batchRemove")
    @RequiresPermissions("grade:teacher:remove")
    public R batchRemove(@RequestParam("ids[]") Long[] ids) {

        teacherService.removeByIds(ids);

        return R.ok();
    }

    /**
    * @Description:上传
    * @Param:
    * @Return:
    * @Author: HighJ
    * @Date Created in
    */

    @RequestMapping("/upload")
    @RequiresPermissions("grade:teacher:remove")
    public R upload(@RequestParam MultipartFile file,HttpServletRequest request)throws Exception{
        String pathFile= FileUtil.saveFile(file);

        return R.ok("data",pathFile);
    }

    /**
     * 导出Excel
     *
     * @param
     * @param response
     * @return
     * @throws Exception
     * @author
     */
    @RequestMapping(value = "exportExcel")
    @RequiresPermissions("grade:teacher:excel")
    public void exportExcel(@RequestParam("where") String where,
                            @RequestParam("pageSize") Integer pageSize,
                            @RequestParam("pageIndex") Integer pageIndex,
                            @RequestParam("sort") String sort,
                            @RequestParam("direct") String direct,
                            HttpServletResponse response) throws Exception {

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding( "utf-8");

        QueryPagePara mQuery = QueryParaHelper.GenQuery(where, pageSize, pageIndex, sort, direct);

        IPage<TeacherDO> teacherDOList = teacherService.getByPage(mQuery);

        String fileName = URLEncoder.encode("教师表","UTF-8").replace("\\+","%20");
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");
        EasyExcel.write(response.getOutputStream(),TeacherDO.class).sheet("模板").doWrite(teacherDOList.getRecords());
    }

    @PostMapping(value = "importExcel")
    @RequiresPermissions("grade:teacher:excel")
    public void  importExcel(@RequestParam MultipartFile file, HttpServletRequest request) throws Exception {
        Integer pageSize = 10;
        //File excelFile= FileUtil.transferToFile(file);

        ExcelUtil.read(file.getInputStream(), TeacherDO.class, pageSize, pageList -> {

           Integer totalRows = teacherService.BatchInsertList(pageList);

            //log.info("读取到数据:[size={}]{}", pageList.size(), pageList); // or demoDataService.save(pageList);
        }).sheet().doRead();
    }

}
